// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import ComponentBase from "../../general/Script/component/ComponentBase";
import { AssetsMgr, g_bundleName, resType } from "../../general/Script/mgr/assetsManager";
import GameMgr from "../../general/Script/mgr/gameManager";
import NativeMgr from "../../general/Script/mgr/nativeManager";
import SoundMgr from "../../general/Script/mgr/soundManager";

import { eHotUpdateEvent } from "../../general/Script/update/HotUpdateEvent";
import { MainHotUpdate } from "../../general/Script/update/MainHotUpdate";
import { Game_Const } from "../../general/Script/update/ManifestInfo";




const { ccclass, property } = cc._decorator;

@ccclass
export default class Update extends ComponentBase {
    progress: cc.Node

    mianHotUpdateCtrl: MainHotUpdate = null;
    onLoad() {
        super.onLoad()

        this.initNativeMsg();


    }

    async start() {


        if (cc.sys.isNative) {
            this.checkMainUpdate();

        } else {
            this.testProgress(() => {
                this.gotoLogin();
            })

        }


    }


    /**
     * 检查主包热更新
     */
    async checkMainUpdate() {
        let mianHotUpdateCtrl = new MainHotUpdate();
        this.mianHotUpdateCtrl = mianHotUpdateCtrl;
        try {
            let packageUrl = `${Game_Const.server_ip}/main`;
            if (packageUrl[packageUrl.length - 2] != "/") {
                packageUrl += "/";
            }
            await mianHotUpdateCtrl.init(packageUrl);
            mianHotUpdateCtrl.checkUpdate();
        } catch (error) {
            throw error;
        }
    }



    initNativeMsg() {
        cc.systemEvent.on(eHotUpdateEvent.mainHotUpdateRate, this.onMainHotUpdateRate, this);
        cc.systemEvent.on(eHotUpdateEvent.mainHotUpdateFinish, this.onMainHotUpdateFinish, this);
        cc.systemEvent.on(eHotUpdateEvent.mainCheckVersionResult, this.onMainCheckVersionResult, this);


    }

    /**
         * 主包热更新新版本检查结果
         *
         * @param newVersionFound 是否发现新版本
         */
    onMainCheckVersionResult(newVersionFound: boolean) {
        if (newVersionFound) {
            this.mianHotUpdateCtrl.hotUpdate();
        } else {
            // 如果不存在新版本，则进入游戏
            this.gotoLogin();
        }
    }

    /**
     * 主包热更新进度回调
     * @param rate
     */
    onMainHotUpdateRate(rate: number) {
        rate = Math.min(rate, 0.97);
        this.progress.getComponent(cc.ProgressBar).progress = rate;
        this.progress.getChildByName("label").getComponent(cc.Label).string = (rate * 100).toFixed(0) + "%"
        // this.rateLabel.string = (rate * 100).toFixed(0) + "%";
    }

    /**
     * 主包热更完成
     */
    onMainHotUpdateFinish() {
        // this.rateLabel.string = "100%";
        this.progress.getComponent(cc.ProgressBar).progress = 1;
        this.progress.getChildByName("label").getComponent(cc.Label).string = "97%";
    }


    async gotoLogin() {
        console.log('login++++++++++++');


        SoundMgr.Ins().initAudioclip(g_bundleName.resources, 'music');

        this.progress.getComponent(cc.ProgressBar).progress = 0.98;
        this.progress.getChildByName("label").getComponent(cc.Label).string = "98%"

        await AssetsMgr.obj().loadBundle(g_bundleName.login)
        await AssetsMgr.obj().preLoadRes(resType.dir, g_bundleName.login, 'Prefab');

        await SoundMgr.Ins().initAudioclip(g_bundleName.login, 'music');
        this.progress.getComponent(cc.ProgressBar).progress = 0.99;
        this.progress.getChildByName("label").getComponent(cc.Label).string = "99%"

        await AssetsMgr.obj().loadBundle(g_bundleName.home)
        await AssetsMgr.obj().preLoadRes(resType.dir, g_bundleName.home, 'Prefab');

        await SoundMgr.Ins().initAudioclip(g_bundleName.home, 'music');
        this.progress.getComponent(cc.ProgressBar).progress = 1;
        this.progress.getChildByName("label").getComponent(cc.Label).string = "100%"
        cc.director.loadScene('login');
    }


    testProgress(cb) {
        const def = 0.05;
        let times = 1;
        this.schedule(() => {
            cc.systemEvent.emit(eHotUpdateEvent.mainHotUpdateRate, times * def);
            times++;
            if (times * def > 1) {
                this.unscheduleAllCallbacks();
                cc.systemEvent.emit(eHotUpdateEvent.mainHotUpdateFinish);
                cb && cb();
            }
        }, 0.1, 100)
    }


    onDestroy(): void {

        cc.systemEvent.targetOff(this);
        this.mianHotUpdateCtrl && this.mianHotUpdateCtrl.destroy();
    }

}
